package com.bs.manager04.utils.interceptor;

import com.bs.manager04.entity.User;
import com.bs.manager04.utils.auth.Auth;
import com.bs.manager04.utils.exception.NoAuthException;
import com.bs.manager04.utils.exception.NotUserNullException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @author 小姚
 * @pakeageName:com.bs.manager04.utils.interceptor
 * @ClassName:MyInterceptor
 * @Descirption:
 * @data 2022/12/17 21:13
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        //如果当前请求的不是一个方法，则直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod method=(HandlerMethod) handler;
        Method method1 = method.getMethod();
        Auth auth = method1.getDeclaredAnnotation(Auth.class);
        if(auth!=null){
            User user =(User) session.getAttribute("user");
            if(user!=null){
                String value = auth.value();
                if(user.getPremission().contains(value)){
                    return true;
                }else{
                    throw new NoAuthException("您没有访问的权限");
                }
            }else{
                throw new NotUserNullException("您还未登录，请确认登录后，再访问");
            }

        }else{
             return true;
        }

    }
}
